
import YYYConfig from "./YYYConfig";

export default class PopUpManager extends Laya.Sprite {
    bgImg: Laya.Sprite;

    auto_close:boolean;
    popup_bg_img:string;
    //"setting/zz_bg.png"
    /**
     * 设置背景遮罩资源
     * **/
    constructor(config: YYYConfig) {
        super();
        this.popup_bg_img = config.popup_bg_img;
        this.auto_close = config.popup_auto_close;
    }
    onAwake(){
        this.bgImg = new Laya.Sprite();
        //绘图的不支持还会有各种问题
        // this.bgImg.graphics.alpha(0.3);
        // this.bgImg.graphics.drawRect(0,0,Laya.stage.width,Laya.stage.height,'#000');
        // this.bgImg.graphics.alpha(1);
        if (this.popup_bg_img) {
            this.bgImg.loadImage(this.popup_bg_img);
            this.bgImg.width = Laya.stage.width;
            this.bgImg.height = Laya.stage.height;
            this.addChild(this.bgImg);

            this.bgImg.on(Laya.Event.MOUSE_DOWN, this, this.noMouse);
            this.bgImg.on(Laya.Event.MOUSE_UP, this, this.noMouse);
            this.bgImg.visible = false;
        }
    }
    noMouse(evt: Laya.Event) {
        if (this.auto_close) {
            this.closeAll();
        }
        evt.stopPropagation();
    }
    open(ui: Laya.Sprite, centerX: boolean = true, centerY: boolean = true): void {
        this.bgImg.visible = true;
        ui.name = "popup_ui";
        //如果这里不做延迟, 宽度就不正常
        const delpay = function () {
            this.addChild(ui);
            if (centerX || centerY) {
                let wh = ui.getBounds();
                if (centerX) {
                    ui.x = (Laya.stage.width - wh.width) / 2;
                    console.log(ui.x);
                }
                if (centerY) {
                    ui.y = (Laya.stage.height - wh.height) / 2;
                }
            }
            Laya.Tween.from(ui, { y: ui.y - Laya.stage.height }, 300, Laya.Ease.cubicIn);
        }
        Laya.timer.frameOnce(1, this, delpay);
    }

    close(ui: Laya.Sprite): void {
        ui.name = "closing_ui";
        Laya.Tween.to(ui, { y: ui.y - Laya.stage.height }, 500, Laya.Ease.cubicOut, Laya.Handler.create(this, this.onClosed, [ui]));
        // ui.removeSelf();
    }

    onClosed(ui: Laya.Sprite): void {
        ui.removeSelf();
        if (this.numChildren < 2) {
            this.bgImg.visible = false;
        }
    }

    closeAll(): void {
        let ui = this.getChildByName('popup_ui');
        while (ui) {
            let sp: Laya.Sprite = ui as Laya.Sprite;
            if (sp) {
                this.close(sp);
            } else {
                ui.removeSelf();
            }
            ui = this.getChildByName('popup_ui');
        }
        this.bgImg.visible = false;
    }

}